package cn.audit.controller;

import cn.audit.aop.myannotation.BussAnnotation;
import cn.audit.bean.pojo.User;
import cn.audit.utils.MD5;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author 李忆枫
 * @date 2019/05/13
 */
@Controller
public class LoginController {


    /**
     * 去登录
     *
     * @return
     */
    @RequestMapping(value = {"/", "toLogin"})
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    /**
     * 登录
     *
     * @return
     */
    @RequestMapping("/login")
    @BussAnnotation(moduleName = "系统", type = "登录", option = "成功")
    public String login(String username, String password, Model model, HttpServletRequest request) {
        /**
         * 使用Shiro编写认证操作
         */
        //1.获取Subject
        Subject subject = SecurityUtils.getSubject();

        //2.封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, MD5.string2MD5(password));

        //3.执行登录方法
        try {
            subject.login(token);
            //session中获取当前登陆的用户信息
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            request.getSession().setAttribute("user", user);
            //登录成功
            return "index";
        } catch (UnknownAccountException e) {
            //登录失败:用户名不存在
            model.addAttribute("nameHint", "用户名不存在");
            return "login";
        } catch (IncorrectCredentialsException e) {
            //登录失败:密码错误
            model.addAttribute("pwdHint", "密码错误");
            return "login";
        }
    }


    /**
     * 注销
     *
     * @return
     */
    @RequestMapping("/logout")
//    @BussAnnotation(moduleName = "系统", type = "注销", option = "成功")
    public String logout(HttpSession session,
                         SessionStatus sessionStatus) {

        Subject subject = SecurityUtils.getSubject();
        subject.logout();

        //销毁session
        try {
            if (session != null) {
                session.removeAttribute("user");
            }
            sessionStatus.setComplete();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "login";
    }


}
